package com.yxw.system.service.impl;

import com.atguigu.model.system.SysRole;
import com.atguigu.model.system.SysUserRole;
import com.atguigu.model.vo.AssginRoleVo;
import com.atguigu.model.vo.SysRoleQueryVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yxw.system.mapper.SysRoleMapper;
import com.yxw.system.mapper.SysUserRoleMapper;
import com.yxw.system.service.SysRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @className: com.yxw.system.service.impl.SysRoleServiceImpl
 * @description: TODO
 * @author: tommy
 * @create: 2023-07-20 下午 09:31
 */
@Service
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements SysRoleService {

   @Autowired
   private SysUserRoleMapper sysUserRoleMapper;

    //条件分页查询
    @Override
    public IPage<SysRole> selectPage(Page<SysRole> pageParam, SysRoleQueryVo sysRoleQueryVo) {
       IPage<SysRole>  pageModel = baseMapper.selectPage(pageParam, sysRoleQueryVo);
        return pageModel;
    }
    //获取用户的角色数据
    @Override
    public Map<String, Object> getRoleByUserId(String userId) {
       //获取所有角色
        List<SysRole> roleList = baseMapper.selectList(null);
        //根据用户id查询，已经分配角色
        QueryWrapper<SysUserRole> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id",userId);
        List<SysUserRole> userRoleList = sysUserRoleMapper.selectList(wrapper);
        //从userRoleList集合获取所有角色id
        ArrayList<Object> userRoleIds = new ArrayList<>();
        for (SysUserRole sysUserRole : userRoleList) {
            String roleId = sysUserRole.getRoleId();
            userRoleIds.add(roleId);
        }
        //封装到map集合
        HashMap<String, Object> map = new HashMap<>();
        map.put("allRoles",roleList);//所有角色
        map.put("userRoleIds",userRoleIds);//用户分配角色id集合
        return map;
    }
   //根据用户分配角色
    @Override
    public void doAssign(AssginRoleVo assginRoleVo) {
        //根据用户id删除之前分配角色
        QueryWrapper<SysUserRole> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id",assginRoleVo.getUserId());
        sysUserRoleMapper.delete(wrapper);

        //获取所有角色id,添加角色用户关系表
        //得到角色id列表
        List<String> roleIdList = assginRoleVo.getRoleIdList();
        for (String roleId : roleIdList) {
            SysUserRole sysUserRole = new SysUserRole();
            sysUserRole.setUserId(assginRoleVo.getUserId());
            sysUserRole.setRoleId(roleId);
            sysUserRoleMapper.insert(sysUserRole);
        }

    }
}
